<template>
  <sys-layout class="sys-page">
    <template v-slot:top>
      <slot name="top">
        <div class="sys-page-tool">
          <el-button icon="el-icon-plus" size="mini" type="primary" @click="$emit('add')" v-if="showAddBtn">新增</el-button>
          <slot name="tools"></slot>
        </div>

        <sys-query v-if="showQuery" ref="query" :model="model" :labelWidth="labelWidth" @query="handleQuery" v-bind="queryProps" v-on="$listeners">
          <template slot="action">
            <slot name="query_action"></slot>
          </template>
          <template slot="actionAppend">
            <slot name="actionAppend"></slot>
          </template>
          <slot name="form"></slot>
          <template slot="form-adv">
            <slot name="form-adv"></slot>
          </template>
          <template slot="toolBar">
            <slot name="toolBar"></slot>
          </template>
        </sys-query>
      </slot>
    </template>

    <template v-if="currshowType === 'table'">
      <my-table ref="table"
                size="mini"
                :fit="fit"
                border
                :columns="columns"
                @select-all="onSelectAll"
                @select="onSelect"
                highlight-current-row
                :loader="loadFn"
                :pageSize="pageSize"
                :pagination="pagination"
                :toolbar="toolbar || selectedAble"
                v-bind="tableProps"
                v-on="tableListeners"
      >
        <!-- my-table的slots -->

        <template >
          <template slot="table-title">
            <slot name="table-title"></slot>

            <!-- 可以选择时现实 -->
            <slot name="table-selected">
              <el-badge v-if="selectedAble" :value="shopList.length">
                <el-button size="small" v-popover:popover>已选择</el-button>
              </el-badge>
            </slot>

          </template>
          <template slot="actions">
            <slot name="table-actions"></slot>
          </template>
        </template>

        <!-- element-table 列的插槽 -->
        <template v-for="(col) in columns" slot-scope="prop" :slot="col.prop" v-if="col.prop">
          <slot :name="col.prop" v-bind="prop">
            {{prop.row[col.prop]}}
          </slot>
        </template>
      </my-table>
    </template>
    <template v-else-if="currshowType === 'cards'">
      <my-cards ref="table" :loader="loadFn" :pageSize="pageSize" :props="cardProps">
        <template v-slot="prop">
          <slot name="card-item" v-bind="prop"></slot>
        </template>
      </my-cards>
    </template>


    <template v-slot:footer>
      <slot name="footer"></slot>
    </template>

    <slot></slot>

    <el-popover
      ref="popover"
      trigger="click"
      placement="right"
      :popper-class="popperClass"
      v-if="selectedAble"
    >
      <div class="sys-page-popover">
        <my-table border fit :columns="currSelectedColumns" :data="shopList" size="mini">
          <template v-slot:ctrl="{row, $index}">
            <el-button type="text" icon="el-icon-delete" size="mini" @click="onRemove(row, $index)">移除</el-button>
          </template>
        </my-table>
      </div>
    </el-popover>

    <!-- 弹窗 -->
    <simple-dialog v-bind.sync="dialog" @on-ok="onDialogOk"/>

  </sys-layout>
</template>

<script>
import myTable from './my-table'
import sysLayout from './sys-layout'
import sysQuery from './sys-query2'
import myCards from './my-cards'

import sysPageSelectMixin from './sys-page-select-mixin'

export default {
  name: 'sys-page',
  cnName: '列表-展示页',
  mixins: [sysPageSelectMixin],
  components: {
    sysLayout,
    myTable,
    sysQuery,
    myCards
  },
  /**
   * 属性参数
   * @member props
   * @property {Boolean} [model] fit，是否高度百分百
   * @property {Object} [model] 表单model
   * @property {String} [labelWidth] 表单labelWidth
   * @property {Function} [showQuery] 是否显示查询
   * @property {Function} [beforeQuery] 查询前事件
   * @property {Object} [queryProps] sysQuery的props
   * @property {Array} [columns] 表格列
   * @property {Function} [loader] 表格请求函数
   * @property {Boolean} [selectedAble] 默认false，如果为true，则提供分页选择功能
   * @property {Boolean} [toolbar] 默认false，对应my-table的toolbar
   * @property {String} [popperClass] 选中数据popper样式类
   * @property {Array} [selectedColumnsRange] 默认[1,3],从columns中截取处对应下表列做选中展示列。会从columns中获取前若干位当做列展示
   * @property {Array} [selectedColumns] 选中表格展示列（优先级高于selectedColumnsNum）
   * @property {Number} [pageSize] 默认页大小
   * @property {Array} [pagination] 分页其他配置
   */
  props: {
    fit: {
      type: Boolean,
      default: true
    },
    model: Object,
    labelWidth: String,
    showQuery: {
      type: Boolean,
      default: true
    },
    beforeQuery: Function,
    queryProps: {
      type: Object
    },
    columns: Array,
    loader: {
      type: Function,
      required: true
    },
    selectedAble: {
      type: Boolean,
      default: false
    },
    toolbar: {
      type: Boolean,
      default: false
    },
    popperClass: String,
    selectedColumnsRange: {
      type: Array,
      default() {
        return [1, 3]
      }
    },
    selectedColumns: {
      type: Array,
      default: null
    },
    tableProps: {
      type: Object
    },
    tableListeners: {
      type: Object
    },
    pageSize: {
      type: Number,
      default: 20
    },
    pagination: {
      type: Object,
      default() {
        return {
          background: true,
          layout: 'total, sizes, ->, prev, pager, next'
        }
      }
    },
    showAddBtn: {
      type: Boolean,
      default: false
    },
    showType: {
      type: String,
      default: 'table'
    },
    cardProps: {
      type: Object
    }
  },
  data() {
    return {
      dialog: {
        title: '',
        visible: false,
        comp: null,
        width: '60%',
        height: '50%',
        props: {}
      },
      currshowType: this.showType
    }
  },
  methods: {
    reload() {
      this.shopList = []
      this.$refs.table && this.$refs.table.refresh(1)
    },
    handleQuery(model) {
      this.$emit('query', model)
      if (this.beforeQuery) {
        this.beforeQuery(model).then(_ => {
          this.reload()
        })
      } else {
        this.reload()
      }
    },
    switchShowType(type) {
      if(type) {
        this.currshowType = type
        return
      }
      if(this.currshowType === 'table') {
        this.currshowType = 'card'
      } else {
        this.currshowType = 'table'
      }
    },
    async loadFn(page, pageSize) {
      const model = this.model
      const res = await this.loader({...model, page, limit: pageSize, pageNum: page, pageSize})
      if(res.page) {
        res.page.total = res.page.totalCount || res.page.total
        return res.page
      } else {
        res.total = res.totalCount || res.total
      }
      if(this.primaryField) {
        this.$nextTick(_ => {
          setTimeout(_ => {
            this.setDataChecked(res.list)
          }, 100)
        })
      }
      return res
    },
    setDialog(options) {
      options.visible = true
      options.width = options.width || '60%'
      options.height = options.height || '70%'

      this.dialog = Object.assign({}, this.dialog, options)
    },
    onDialogOk(data) {
      this.dialog.visible = false
      this.$emit('dialog-ok')
      this.reload()
    },
    onSelectAll(selection) {
      if(!this.selectedAble) {
        this.$emit('select-all', selection)
        return
      }
      this.doSelectAll(selection)
    },
    onSelect(selection) {
      if(!this.selectedAble) {
        this.$emit('select', selection)
        return
      }
      this.doSelect(selection)
    },
    getSelection(type) {
      const shopList = this.shopList
      return new Promise((resolve, reject) => {
        if(shopList.length === 0) {
          this.$modal.notifyWarning('请至少选择一条数据')
          reject()
          return
        }
        if(type === 1) {
          if(shopList.length > 1) {
            this.$modal.notifyWarning('请选择一条数据')
            reject()
            return
          }
          resolve(shopList[0])
          return
        } else {
          resolve(shopList)
        }
      })
    }
  },
  computed: {
    $table() {
      // 获取el-table，因为切换选择框时候需要
      return this.$refs.table && this.$refs.table.$refs.elTable
    },
    currSelectedColumns() {
      if(this.selectedColumns) {
        return this.selectedColumns
      }
      const start = this.selectedColumnsRange[0]
      const end = this.selectedColumnsRange[1]
      const columns = this.columns.slice(start, end)
      columns.push({
        prop: 'ctrl',
        label: '操作',
        align: 'center'
      })
      return columns
    }
  }
}
</script>

<style lang="scss" >
.sys-page {
  padding: 0;

  &-tool {
    border-bottom: 1px solid #ececec;
    border-top: 1px solid #ececec;
    padding: 0 15px;
  }

  &-popover {
    min-width: 400px;
    max-height: 400px;
    overflow: auto;
  }
}
</style>
